//designpatterns.abstractfactory.XMLUtil.java
package org.patterns.creational.abstractfactory;

import java.net.URL;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class XMLUtil {
    //该方法用于从XML配置文件中提取具体类类名，并返回一个实例对象
    public static Object getBean() {
        try {
            // 获取文件的URL
            URL url = XMLUtil.class.getResource("config.xml");
            String filePath = url.getFile();
            System.out.println("文件URL: " + URLDecoder.decode(filePath, StandardCharsets.UTF_8));
            //创建DOM文档对象
            DocumentBuilderFactory dFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = dFactory.newDocumentBuilder();
            Document doc;
            doc = builder.parse(filePath);
            //doc = builder.parse(new File("src/main/resources/org/patterns/creational/abstractfactory/config.xml"));

            // 获取包含类名的文本节点
            NodeList nodes = doc.getElementsByTagName("className");
            if (nodes == null || nodes.getLength() == 0) {
                throw new RuntimeException("XML 中未找到 <className> 节点");
            }
            Node classNode = nodes.item(0).getFirstChild();
            String cName = classNode.getNodeValue().trim();

            // Class clazz = Class.forName(cName);
            // Object obj = clazz.newInstance();
            // 通过类名生成实例对象并将其返回
            Class<?> clazz = Class.forName(cName);
            Object obj = clazz.getDeclaredConstructor().newInstance();
            return obj;
        } catch (Exception ex) {
            ex.printStackTrace();
            return null;
        }
    }
}
